package com.example.libraryapp.network.net;


import com.example.libraryapp.network.base.IHttpListener;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;

/**
 * @author 伍凯铭
 * @since 2020/2/27
 */
public class RxSchedulers {
    public static <T> ObservableTransformer<T,T> applySchedulers(){
        return new ObservableTransformer<T, T>() {
            @Override
            public ObservableSource<T> apply(Observable<T> upstream) {
                return upstream.subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread());
            }
        };
    }

    /**
     * 建立请求
     */
    public static <T> DisposableObserver<T> doRequest(final Observable<T> observable, final IHttpListener<T> observerListener) {

        return observable
                .compose(RxSchedulers.<T>applySchedulers())
                .subscribeWith(new DisposableObserver<T>() {

                    @Override
                    public void onNext(T result) {
                        observerListener.onSuccess(result);
                    }

                    @Override
                    public void onError(Throwable e) {
                        observerListener.onError(e);
                    }

                    @Override
                    public void onComplete() {
                        observerListener.onComplete();
                    }
                });

    }
}
